package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.MessageConst;
import com.itheima.entity.Result;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    OrderSettingService orderSettingService;

    @RequestMapping("/saveOrEdit")
    public Result saveOrEdit(@RequestBody OrderSetting orderSetting){

        orderSettingService.saveOrEdit(orderSetting);

        return new Result(true,"设置成功！");
    }




    @RequestMapping("/findByMonth")
    public Result findByMonth(String date){
        log.debug("获得前端传来的当前月份"+date);
        List<Map<String,Object>> maps = orderSettingService.findByMonth(date);
        return new Result(true,MessageConst.QUERY_MONTH_DATA_SUCCESS,maps);
    }



    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile){
        log.debug("获得文件："+excelFile);
        try {
            List<String[]> strings = POIUtils.readExcel(excelFile);
            List<OrderSetting> orderSettingsList = new ArrayList<>();
            for (String[] str : strings) {
                OrderSetting orderSetting = new OrderSetting();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                Date date = sdf.parse(str[0]);
                System.out.println("注意！注意！注意！转换后的日期样式为 = " + date);
                orderSetting.setOrderDate(date);
               orderSetting.setNumber(Integer.parseInt(str[1]));
               orderSettingsList.add(orderSetting);
            }

            orderSettingService.addOrderSettingList(orderSettingsList);
            return new Result(true, MessageConst.ADD_ORDERSETTINGLIST_SUCCESS);

        } catch (BusinessRuntimeException b) {
            return new Result(false,b.getMessage());
        }  catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ADD_ORDERSETTINGLIST_FATL);
        }
    }


}
